package com.platform.cdcs.fragment.custom;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.choose.AccountChooseFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/11/20.
 */
public class AddCustomFragment extends BaseFragment {

    private EditText nameET, codeET, custCodeET, custNameET, unitET, accountNameET, accountCodeET, lineCodeET, lineNameET;
    private EditText addressET, typeET, numberET, code1ET, unit1ET, markET;
    private String[] unitArray;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        setTitle("新增产品");
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        initLoadImg(view.findViewById(R.id.load));
        view.findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                post();
            }
        });
        LayoutInflater inflater = LayoutInflater.from(getContext());
        LinearLayout root1 = (LinearLayout) view.findViewById(R.id.button1);
        nameET = ViewTool.createEditItem(inflater, "标准名称", root1, true, true);
        nameET.setHint("请选择产品");
        nameET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("class", AddCustomFragment.this.getClass().getName());
                FragmentUtil.navigateToInNewActivity(getActivity(), ProSearchListFragment.class, bundle);
            }
        });

        codeET = ViewTool.createEditItem(inflater, "标准代码", root1, true, true);
        codeET.setEnabled(false);
        custCodeET = ViewTool.createEditItem(inflater, "自定义产品代码", root1, true, false);
        custCodeET.setHint("自定义产品代码");
        custNameET = ViewTool.createEditItem(inflater, "自定义产品名称", root1, true, false);
        custNameET.setHint("自定义产品名称");
        unitET = ViewTool.createEditItemNoLine(inflater, "默认单位", root1, true, true);
        unitET.setHint("请选择单位");
        unitET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUnit();
            }
        });

        LinearLayout root2 = (LinearLayout) view.findViewById(R.id.button2);
        accountNameET = ViewTool.createEditItem(inflater, "客户名称", root2, false, true);
        accountNameET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putInt("model", 0);
                bundle.putString("class", AddCustomFragment.this.getClass().getName());
                FragmentUtil.navigateToInNewActivity(getActivity(), AccountChooseFragment.class, bundle);
            }
        });
        accountCodeET = ViewTool.createEditItemNoLine(inflater, "客户代码", root2, false, true);
        accountCodeET.setEnabled(false);

        LinearLayout root3 = (LinearLayout) view.findViewById(R.id.button3);
        lineCodeET = ViewTool.createEditItem(inflater, "产品线", root3, false, false);
        lineCodeET.setEnabled(false);
        lineNameET = ViewTool.createEditItemNoLine(inflater, "产品线名称", root3, false, false);
        lineNameET.setEnabled(false);

        LinearLayout root4 = (LinearLayout) view.findViewById(R.id.button4);
        addressET = ViewTool.createEditItem(inflater, "产地", root4, false, false);
        addressET.setHint("请输入产地");
        typeET = ViewTool.createEditItem(inflater, "灭菌方式", root4, false, false);
        typeET.setHint("请输入灭菌方式");
        numberET = ViewTool.createEditItem(inflater, "医保编号", root4, false, false);
        numberET.setHint("请输入医保编号");
        code1ET = ViewTool.createEditItem(inflater, "医院物料代码", root4, false, false);
        code1ET.setHint("请输入医院物料代码");
        unit1ET = ViewTool.createEditItemNoLine(inflater, "医院物料单位", root4, false, false);
        unit1ET.setHint("请输入医院物料单位");

        LinearLayout root5 = (LinearLayout) view.findViewById(R.id.button5);
        markET = ViewTool.createEditItemNoLine(inflater, "备注", root5, false, false);
        markET.setHint("请输入备注");
    }

    @Override
    public int layoutId() {
        return R.layout.five_layout;
    }

    private void post() {
        if (TextUtils.isEmpty(codeET.getText().toString().trim())) {
            Utils.showToast(getContext(), "标准名称不能为空!");
            return;
        }
        if (TextUtils.isEmpty(custCodeET.getText().toString().trim())) {
            Utils.showToast(getContext(), "自定义产品代码不能为空!");
            return;
        }
        if (TextUtils.isEmpty(custNameET.getText().toString().trim())) {
            Utils.showToast(getContext(), "自定义产品名称不能为空!");
            return;
        }
        if (TextUtils.isEmpty(unitET.getText().toString().trim())) {
            Utils.showToast(getContext(), "默认单位不能为空!");
            return;
        }
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("updateType", "2");
        param.put("materialStCode", codeET.getText().toString().trim());
        param.put("materialCNDesc", nameET.getText().toString().trim());
        param.put("materialNumber", custCodeET.getText().toString().trim());
        param.put("materialName", custNameET.getText().toString().trim());

//        param.put("level2", lineCodeET.getText().toString().trim());
        param.put("defaultUnit", (String) unitET.getTag());
        param.put("cusName", accountNameET.getText().toString().trim());
        param.put("origin", addressET.getText().toString().trim());
        param.put("sterilization", typeET.getText().toString().trim());
        param.put("medicalNumber", numberET.getText().toString().trim());
        param.put("hospitalMaterial", code1ET.getText().toString().trim());
        param.put("hospitalMunit", unit1ET.getText().toString().trim());
        param.put("remark", markET.getText().toString().trim());
        getHttpClient().post().url(Constant.UPDATE_DIST_PRODUCT).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                    }.getType();
                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        Utils.showToast(getContext(), "添加成功！");
                        RefershEvent event = new RefershEvent();
                        event.mclass = CustomProFragment.class;
                        EventBus.getDefault().post(event);
                        getActivity().finish();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "提交失败!");
                }
            }
        });
    }


    private void requestUnit() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "3");
        map.put("itemCode", codeET.getText().toString());
//        map.put("itemCode", "HP054");
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        JSONArray jsonArray = obj.getJSONArray("uomList");
                        unitArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            if (!TextUtils.isEmpty(jsonArray.getJSONObject(j).getString("uomName"))) {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " (" + jsonArray.getJSONObject(j).getString("uomName") + ")";
                            } else {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " ";
                            }
                        }
                        showUnit();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                    unitArray = null;
                }
            }
        });
    }

    private void showUnit() {
        if (TextUtils.isEmpty(codeET.getText().toString())) {
            Utils.showToast(getContext(), "标准名称不能为空！");
            return;
        }
        if (unitArray == null) {
            requestUnit();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择单位", unitArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    unitET.setText(unitArray[i]);
                    unitET.setTag(unitArray[i].split(" ")[0]);
                }
            }).create().show();
        }
    }


    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            if (event.oclass == ProSearchListFragment.class) {
                ProductList.ProductItem item = (ProductList.ProductItem) event.bundle.getSerializable("model");
                nameET.setText(item.getItemName());
                codeET.setText(item.getItemCode());
                lineNameET.setText(item.getSubBUName());
                lineCodeET.setText(item.getSubBUCode());
                unitET.setText("");
                unitArray = null;
            } else if (event.oclass == AccountChooseFragment.class) {
                String cusCode = event.bundle.getString("code");
                String cusName = event.bundle.getString("name");
                accountNameET.setText(cusName);
                accountCodeET.setText(cusCode);
            }
        }
    }
}
